import Vue from "vue";
import VueRouter from "vue-router";
import Login from "@/views/Login.vue";
// 获取原型对象push函数
const originalPush = VueRouter.prototype.push

// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location){
return originalPush.call(this , location).catch(err=>err)
}

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replace(location){
return originalReplace.call(this , location).catch(err=>err)
}
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Login",
    component: Login,
    meta: {
      needTooken: false,
      type: "web",
    },
  },
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/Layout"),
    meta: {
      needTooken: true,
      type: "web",
    },
    redirect: "/main",
    children: [
      {
        path: "/main",
        name: "main",
        component: () => import("@/views/Record"),
        meta: {
          needTooken: true,
          type: "web",
        },
      },
      {
        path: "/userList",
        name: "userList",
        component: () => import("@/views/UserList"),
        meta: {
          needTooken: true,
          type: "web",
        },
      },
      {
        path: "/report/:id",
        name: "report3",
        component: () => import("@/views/Report"),
        meta: {
          needTooken: true,
          type: "web",
        },
      },
    ],
  },

  {
    path: "/notfound",
    name: "notfound",
    component: () => import("@/views/NotFound"),
    meta: {
      needTooken: false,
      type: "web",
    },
  },
  {
    path: "*",
    redirect(to) {
      if (to.path == "/") {
        return "/";
      } else {
        return "/notFound";
      }
    },
  },
];

const router = new VueRouter({
  routes,
});
router.beforeEach((to, from, next) => {
  if (to.meta.needTooken) {
    const token = window.sessionStorage.getItem("token");
    if (token) {
      const authorization = JSON.parse(token).authorization;
      if (authorization) {
        next();
      } else {
        //返回登录页面
        next({
          path: "/",
        });
      }
    } else {
      //返回登录页面
      next({
        path: "/",
      });
    }
  } else {
    next();
  }
});
export default router;
